package test.my_filter;

import org.springframework.stereotype.Component;
import test.config.ProjectUrlConfig;
import test.domin.User;
import test.enumeration.PermTypeEnum;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : example
 * @ Author: XuLeHuang
 * @ Date: 2022/6/25 10:50
 * @ Description:
 */
@WebFilter(urlPatterns = { "/auth/validate"}, filterName="whitelistFilter")
public class WhitelistFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化后被调用一次
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException, IOException {
        // 判断是否需要拦截
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        HttpSession session = httpServletRequest.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            httpServletResponse.sendRedirect(ProjectUrlConfig.LOGIN);

        } else if (!PermTypeEnum.admin.getCode().equals(user.getPerm())) {
            httpServletResponse.sendRedirect(ProjectUrlConfig.ANON);
        } else {
            chain.doFilter(request, response); // 请求通过要显示调用,不调用则说明不通过，可以指定页面返回
        }

    }

    @Override
    public void destroy() {
        // 被销毁时调用一次
    }
}
